﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Web.SessionState;
using fbasync.web.Data;
using System.Text;

namespace fbasync.web
{
    public class ApplicationConfigHandler : IHttpHandler, IRequiresSessionState
    {

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        private string GetFormattedXml(XmlDocument document)
        {
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            
            StringBuilder builder = new StringBuilder();

            XmlWriter writer = XmlWriter.Create(builder, settings);

            document.WriteTo(writer);

            writer.Flush();

            return builder.ToString();
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ClearContent();
            context.Response.CacheControl = "no-cache";
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.Cache.SetExpires(DateTime.Now.AddMonths(-1));
            context.Response.AddHeader("Cache-Control", "no-cache");

            string localPath = context.Request.Url.LocalPath;
            int fileNameStart = localPath.LastIndexOf("/");

            string appName = localPath.Substring(fileNameStart + 1, localPath.LastIndexOf(".") - fileNameStart - 1);

            XmlDocument exportDocument = TemplateEditorDataAccess.ExportFBConfig(appName);

            string result = String.Empty;

            result += GetFormattedXml(exportDocument);

            context.Response.ContentType = "text/xml";
            context.Response.Write(result);
        }

        #endregion
    }
}
